/*
 * cbuf.c
 *
 * Created: 2013/12/21 10:56:58
 *  Author: Developer
 */ 
#include "cbuf.h"

#define CBUF_PLUS(VAL, LEN)		VAL = (VAL + 1) % LEN
#define IS_BUFFER_FULL(CBUF) \
	((((CBUF->writeCount + 1) % CBUF->phyLength) == CBUF->readCount) ? 1 : 0)
	

int getDataCount(cbuf_t *cbuf) {
	int delta = cbuf->writeCount - cbuf->readCount;
	
	return (delta >= 0) ? delta : cbuf->phyLength + delta;
}

int getEmptyCount(cbuf_t *cbuf) {
	int delta = cbuf->writeCount - cbuf->readCount;
	
	return (delta >= 0) ? cbuf->phyLength - delta - 1 : -1 * (delta + 1);
}

void CBufInit(cbuf_t *cbuf, char *buffer, int bufferLen) {
	cbuf->baseAddr = buffer;
	cbuf->phyLength = bufferLen;
	cbuf->readCount = 0;
	cbuf->writeCount = 0;
}

int CBufWrite(cbuf_t *cbuf, const char *writeBuffer, int bufferLengthByte) {
	int nByte;
	
	nByte = getEmptyCount(cbuf);
	
	if(bufferLengthByte > nByte)
		bufferLengthByte = nByte;
	
	nByte = bufferLengthByte;
	while (bufferLengthByte --) {
		cbuf->baseAddr[cbuf->writeCount] = *writeBuffer ++;
		CBUF_PLUS(cbuf->writeCount, cbuf->phyLength);
	}
	return nByte;
}

int CBufRead(cbuf_t *cbuf, char *readBuffer, int bufferLengthByte) {
	int nByte;
	
	nByte = getDataCount(cbuf);
	
	if(bufferLengthByte > nByte)
		bufferLengthByte = nByte;
	
	nByte = bufferLengthByte;
	while (bufferLengthByte --) {
		*readBuffer ++ = cbuf->baseAddr[cbuf->readCount];
		CBUF_PLUS(cbuf->readCount, cbuf->phyLength);
	}
	return nByte;
}

//#if (0)
//#include "uart.h"
//#include <stdio.h>
//#include <string.h>
//void CBufMain(void) {
	//cbuf_t mBuffer = {0};
	//int w;
	//int r;
	//
	//// mBuffer.baseAddr = malloc(6);
	//uart1_open(115200);
//
	////mBuffer.phyLength = 6;
	////while (1) {
		////w = uart1_getc(-1);
		////w -= '0';
		////kprintf("w=%d ", w);
		////
		////r = uart1_getc(-1);
		////r -= '0';
		////kprintf("r=%d ", r);
		////
		////mBuffer.readCount = r;
		////mBuffer.writeCount = w;
		////
		////kprintf("data=%d ", getDataCount(&mBuffer));
		////kprintf("empty=%d\r\n", getEmptyCount(&mBuffer));
	////}
//
	//
	//while(1);
//}
//#endif
